"""详情面板组件模块"""

from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QTextEdit
)
from PySide6.QtCore import Qt, QSize, QPropertyAnimation, QEasingCurve
from PySide6.QtGui import QFont, QIcon, QPixmap, QPainter, QPen
import base64

from .search_widget import SearchWidget


class CollapsibleDetailPanel(QWidget):
    """可折叠的详情面板"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.is_expanded = False  # 默认收缩状态
        self.animation = None
        self.main_window = None  # 主窗口引用
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 标题栏（包含箭头和标题）
        self.title_bar = QWidget()
        self.title_bar.setFixedHeight(28)  # 从35减少到28
        self.title_bar.setStyleSheet("""
            QWidget {
                background-color: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 4px;
            }
            QWidget:hover {
                background-color: #e9ecef;
            }
        """)
        
        title_layout = QHBoxLayout()
        title_layout.setContentsMargins(8, 3, 8, 3)  # 减少边距
        
        # 箭头按钮
        self.arrow_button = QPushButton()
        self.arrow_button.setFixedSize(16, 16)  # 从20x20减少到16x16
        self.arrow_button.setIcon(self.create_arrow_icon(False))
        self.arrow_button.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                border: none;
                border-radius: 3px;
            }
            QPushButton:hover {
                background-color: #dee2e6;
            }
        """)
        self.arrow_button.clicked.connect(self.toggle_expansion)
        
        # 标题文本
        self.title_label = QLabel("详细内容")
        self.title_label.setFont(QFont("Arial", 11, QFont.Bold))  # 从12减少到11
        self.title_label.setStyleSheet("color: #333; background-color: transparent;")
        
        # 搜索组件
        self.search_widget = SearchWidget()
        self.search_widget.setMaximumHeight(20)  # 适应title_bar高度
        
        title_layout.addWidget(self.arrow_button)
        title_layout.addWidget(self.title_label)
        title_layout.addStretch()
        title_layout.addWidget(self.search_widget)
        
        self.title_bar.setLayout(title_layout)
        
        # 内容区域
        self.content_widget = QWidget()
        self.content_layout = QVBoxLayout()
        self.content_layout.setContentsMargins(5, 5, 5, 5)  # 减少内容区域边距
        self.content_layout.setSpacing(5)  # 减少间距
        self.content_widget.setLayout(self.content_layout)
        
        # 详细内容显示区域
        self.content_area = QWidget()
        self.content_area_layout = QVBoxLayout()
        self.content_area_layout.setContentsMargins(0, 0, 0, 0)
        self.content_area_layout.setSpacing(5)  # 减少间距
        self.content_area.setLayout(self.content_area_layout)
        
        # 文本内容显示
        self.detail_text = QTextEdit()
        self.detail_text.setReadOnly(True)
        self.detail_text.setMinimumHeight(120)  # 从150减少到120
        self.detail_text.setMaximumHeight(150)  # 设置最大高度限制
        self.detail_text.setStyleSheet("""
            QTextEdit {
                border: 1px solid #dee2e6;
                border-radius: 4px;
                background-color: #f8f9fa;
                font-family: '微软雅黑', 'Microsoft YaHei', sans-serif;
                font-size: 12px;
                padding: 5px;
            }
        """)
        
        # 图片预览标签
        self.image_preview = QLabel()
        self.image_preview.setAlignment(Qt.AlignCenter)
        self.image_preview.setMinimumHeight(120)  # 设置最小高度
        self.image_preview.setMaximumHeight(150)  # 设置最大高度
        self.image_preview.setStyleSheet("""
            QLabel {
                border: 1px solid #dee2e6;
                border-radius: 4px;
                background-color: #ffffff;
                padding: 5px;
            }
        """)
        self.image_preview.hide()
        
        self.content_area_layout.addWidget(self.detail_text)
        self.content_area_layout.addWidget(self.image_preview)
        
        # 操作按钮 - 更紧凑的布局
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 0, 0, 0)
        button_layout.setSpacing(8)  # 减少按钮间距
        
        self.copy_button = QPushButton("复制")  # 简化按钮文本
        self.copy_button.setEnabled(False)
        self.copy_button.setMaximumWidth(60)  # 限制按钮宽度
        
        self.delete_button = QPushButton("删除")
        self.delete_button.setEnabled(False)
        self.delete_button.setMaximumWidth(60)
        
        self.clear_button = QPushButton("清空")  # 简化按钮文本
        self.clear_button.setMaximumWidth(60)
        
        button_layout.addWidget(self.copy_button)
        button_layout.addWidget(self.delete_button)
        button_layout.addStretch()
        button_layout.addWidget(self.clear_button)
        
        self.content_layout.addWidget(self.content_area)
        self.content_layout.addLayout(button_layout)
        
        # 默认隐藏内容
        self.content_widget.hide()
        self.content_widget.setMaximumHeight(0)
        
        layout.addWidget(self.title_bar)
        layout.addWidget(self.content_widget)
        self.setLayout(layout)
        
        # 设置鼠标光标
        self.title_bar.setCursor(Qt.PointingHandCursor)
        
        # 为标题栏添加点击事件
        self.title_bar.mousePressEvent = self.on_title_bar_clicked
        
    def create_arrow_icon(self, is_expanded: bool) -> QIcon:
        """创建箭头图标"""
        pixmap = QPixmap(16, 16)
        pixmap.fill(Qt.transparent)
        
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(Qt.black, 2))
        
        if is_expanded:
            # 向下的箭头（展开状态）
            painter.drawLine(4, 6, 8, 10)
            painter.drawLine(8, 10, 12, 6)
        else:
            # 向右的箭头（收缩状态）
            painter.drawLine(6, 4, 10, 8)
            painter.drawLine(10, 8, 6, 12)
        
        painter.end()
        return QIcon(pixmap)
    
    def on_title_bar_clicked(self, event):
        """标题栏点击事件"""
        if event.button() == Qt.LeftButton:
            self.toggle_expansion()
    
    def toggle_expansion(self):
        """切换展开/收缩状态"""
        if self.is_expanded:
            self.collapse()
        else:
            self.expand()
    
    def expand(self):
        """展开详情面板"""
        if self.is_expanded:
            return
            
        self.is_expanded = True
        self.arrow_button.setIcon(self.create_arrow_icon(True))
        
        # 显示内容widget
        self.content_widget.show()
        
        # 获取当前主窗口大小
        if self.main_window:
            current_size = self.main_window.size()
            target_height = current_size.height() + 200  # 从250减少到200
            
            # 创建窗口大小调整动画
            self.animation = QPropertyAnimation(self.main_window, b"size")
            self.animation.setDuration(300)
            self.animation.setStartValue(current_size)
            self.animation.setEndValue(QSize(current_size.width(), target_height))
            self.animation.setEasingCurve(QEasingCurve.OutCubic)
            self.animation.start()
        
        # 同时显示内容
        self.content_widget.setMaximumHeight(200)  # 从250减少到200
    
    def collapse(self):
        """收缩详情面板"""
        if not self.is_expanded:
            return
            
        self.is_expanded = False
        self.arrow_button.setIcon(self.create_arrow_icon(False))
        
        # 获取当前主窗口大小
        if self.main_window:
            current_size = self.main_window.size()
            target_height = current_size.height() - 200  # 从250减少到200
            
            # 创建窗口大小调整动画
            self.animation = QPropertyAnimation(self.main_window, b"size")
            self.animation.setDuration(300)
            self.animation.setStartValue(current_size)
            self.animation.setEndValue(QSize(current_size.width(), target_height))
            self.animation.setEasingCurve(QEasingCurve.InCubic)
            
            # 动画完成后隐藏widget
            self.animation.finished.connect(self._on_collapse_finished)
            self.animation.start()
        else:
            self._on_collapse_finished()
    
    def _on_collapse_finished(self):
        """收缩动画完成后的处理"""
        self.content_widget.hide()
        self.content_widget.setMaximumHeight(0)
        # 断开信号连接，避免重复连接
        if self.animation:
            self.animation.finished.disconnect()
    
    def set_content(self, content: str, content_type: str = "text"):
        """设置详细内容"""
        if content_type == "image":
            # 显示图片预览
            self.show_image_preview(content)
            self.detail_text.hide()
            self.image_preview.show()
        else:
            # 显示文本内容
            self.detail_text.setPlainText(content)
            self.detail_text.show()
            self.image_preview.hide()
    
    def show_image_preview(self, image_data: str):
        """显示图片预览"""
        try:
            if image_data.startswith("data:image"):
                # 解析base64图片数据
                base64_data = image_data.split(",")[1]
                img_data = base64.b64decode(base64_data)
                
                # 创建QPixmap
                pixmap = QPixmap()
                pixmap.loadFromData(img_data)
                
                if not pixmap.isNull():
                    # 创建适合显示的预览图
                    max_size = 200
                    scaled_pixmap = pixmap.scaled(
                        max_size, max_size, 
                        Qt.KeepAspectRatio, 
                        Qt.SmoothTransformation
                    )
                    self.image_preview.setPixmap(scaled_pixmap)
                    
                    # 显示图片信息
                    info_text = f"图片尺寸: {pixmap.width()} × {pixmap.height()}"
                    self.image_preview.setToolTip(info_text)
                else:
                    self.image_preview.setText("无法显示图片")
            else:
                self.image_preview.setText("无效的图片数据")
                
        except Exception as e:
            print(f"显示图片预览失败: {e}")
            self.image_preview.setText("图片预览失败")
    
    def clear_content(self):
        """清空内容"""
        self.detail_text.clear()
        self.image_preview.clear()
        self.image_preview.hide()
        self.detail_text.show()
    
    def get_buttons(self):
        """获取操作按钮"""
        return self.copy_button, self.delete_button, self.clear_button
    
    def get_search_widget(self):
        """获取搜索组件"""
        return self.search_widget 